package com.jbp.utils;

import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class GeneratorRSAKey {

    public static  final String publicKey="MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJakeyXtC5SZdo7BWY9wA0e3RVKpBcziLH2BtCXcFYHweUg7Y8NYYZx7O4GrIfnwq3bo0lXOVdEs+WdROyWBLmMCAwEAAQ==";
    public static final String privateKey="MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAlqR7Je0LlJl2jsFZj3ADR7dFUqkFzOIsfYG0JdwVgfB5SDtjw1hhnHs7gash+fCrdujSVc5V0Sz5Z1E7JYEuYwIDAQABAkAsT1M905zdZ8p8sRiz3UHJvXmxl6/yFPD7NcSUgkj9QBcVPSRpWVviwtPT4JzS/7IbSLHkqxFQFv9mK0MJIg35AiEA3/8a/+ww/e0yr2I1XXZXDyQlx/7EAME9F+7yiN54beUCIQCsKmFSKHvtXvS+BSIROZVR3LfKMUJSQhCwdunh1AOmpwIgWLGMoVWGuKUZcrSyaMWZB1fK1fwc5Cef50AoLOXaTbkCIDOOCVCZ8OpW+gEA9n+j97Po3Vx9vbd2Mxs0sLrAS0uXAiEAogMPw26ltEotAy2g3DHidNgncdAj3+cunJFFSa4vryE=";
    public static void main(String[] args)throws Exception {

        //jdkRSA();

        String res="aaaaaaaaaaaaaabbbbbbbbbb";
        res= encrypt(res,publicKey);
        System.out.println(res);
        res= decrypt(res,privateKey);
        System.out.println(res);

    }

    public static void jdkRSA() {
        GeneratorRSAKey generatorKey = new GeneratorRSAKey();

        try {
            // 初始化密钥，产生公钥私钥对
            Object[] keyPairArr = generatorKey.initSecretkey();
            RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPairArr[0];
            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPairArr[1];

            System.out.println("------------------PublicKey------------------");
            System.out.println(new String(Base64.encodeBase64(rsaPublicKey.getEncoded())));

            System.out.println("\n------------------PrivateKey------------------");
            System.out.println(new String(Base64.encodeBase64(rsaPrivateKey.getEncoded())));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化密钥，生成公钥私钥对
     *
     * @return Object[]
     * @throws NoSuchAlgorithmException NoSuchAlgorithmException
     */
    private Object[] initSecretkey() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(512);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();

        Object[] keyPairArr = new Object[2];
        keyPairArr[0] = rsaPublicKey;
        keyPairArr[1] = rsaPrivateKey;

        return keyPairArr;
    }

    //加密
    public static String encrypt(String str, String publicKey)
            throws Exception
    {
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(1, pubKey);
        String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        return outStr;
    }

    //解密
    public static String decrypt(String str, String privateKey)
            throws Exception
    {
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));

        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey)KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(2, priKey);
        String outStr = new String(cipher.doFinal(inputByte));
        return outStr;
    }

}
